import re

from rest_framework import serializers


from users.models import User

'''
１　那些参数需要校验　数据库中没有这个字段　
２　用户名　密码　密码２　手机号　短信验证码　ａｌｌｏｗ　
３　没有的　密码２　短信验证码　ａｌｌｏｗ
４　

'''


class ResgisterUserAPIViewSerializer(serializers.ModelSerializer):

    sms_code = serializers.CharField(required=True,min_length=6,max_length=6,label='短信验证码',write_only=True)
    password2 = serializers.CharField(required=True,min_length=8,max_length=20,label='密码',write_only=True)
    allow = serializers.CharField(required=True,label='协议',write_only=True)


    class Meta:
        model = User
        fields = ['sms_code','allow','password','password2','username','mobile']
        extra_kwargs = {
            'id': {'read_only': True},
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    def validated_mobile(self,value):

        if re.match(r'1[3456789]\d{9}',value):
            raise serializers.ValidationError('手机号格式不正确')

        return value

    def validate(self, attrs):
        password = attrs.get('password')
        password2 = attrs.get('password2')

        if password!=password2:
            raise serializers.ValidationError('两次密码输入不一致')

        allow = attrs.get('allow')

        if allow != 'True':
            raise serializers.ValidationError('没有同意协议')

        sms_code = attrs.get('sms_code')

        from django_redis import get_redis_connection

        redis_conn = get_redis_connection('code')
        mobile = attrs.get('mobile')

        redis_sms_code = redis_conn.get('sms_code_%s'%mobile)

        if redis_sms_code is None:
            raise serializers.ValidationError('短信验证码过期')

        if redis_sms_code.decode()!=sms_code:
            raise serializers.ValidationError('短信验证码输入错误')

        return attrs

    def create(self, validated_data):

        del validated_data['sms_code']
        del validated_data['password2']
        del validated_data['allow']

        user = User.objects.create(**validated_data)

        user.set_password(validated_data['password'])

        token = jwtvalue(user)
        user.token = token

        user.save()

        return user


# 封装　JWT
def jwtvalue(value):
    from rest_framework_jwt.settings import api_settings
    jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
    jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
    payload = jwt_payload_handler(value)
    token = jwt_encode_handler(payload)

    return token